package com.ccteam.fluidmusic.view.adapters.onlinehome

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.ccteam.fluidmusic.R
import com.ccteam.fluidmusic.databinding.OnlineMusicHomeInnerSmallItemBinding
import com.ccteam.fluidmusic.databinding.OnlineMusicHomeOtherSmallItemBinding
import com.ccteam.fluidmusic.databinding.OnlineMusicHomeTypeBrowseItemBinding
import com.ccteam.fluidmusic.view.adapters.BannerCallback
import com.ccteam.fluidmusic.view.adapters.BannerShapeImageAdapter
import com.ccteam.fluidmusic.view.adapters.ViewBindViewHolder
import com.ccteam.fluidmusic.view.adapters.viewbinding.MultiTypeViewBindingAdapter
import com.ccteam.fluidmusic.view.adapters.viewbinding.ViewBindingAdapter
import com.ccteam.shared.result.BaseItemData
import com.ccteam.shared.result.home.OnlineMusicHomeInnerSmallItem
import com.ccteam.shared.result.home.OnlineMusicHomeSmallItem
import com.ccteam.shared.result.home.OnlineMusicHomeTypeBrowseItem
import com.youth.banner.indicator.CircleIndicator

/**
 * @author Xiaoc
 * @since 2021/4/13
 */
/**
 * 在线音乐首页的RecyclerView适配器
 * 其中有不同类型Type的Item项
 * 他们有各自不同的内容
 */
class OnlineMusicHomeRVAdapter(
    private val bannerCallback: BannerCallback,
    private val callback: OnlineMusicHomeSmallItemCallback,
    private val homeItemFunctionCallback: OnlineMusicHomeFunctionCallback
): MultiTypeViewBindingAdapter(OnlineMusicHomeSmallItem.differCallback){

    /**
     * 首页分类浏览视图容器
     */
    inner class TypeBrowseViewHolder(
        binding: OnlineMusicHomeTypeBrowseItemBinding,
        callbackFunction: OnlineMusicHomeFunctionCallback
    ): ViewBindViewHolder<OnlineMusicHomeTypeBrowseItemBinding>(binding){

        init {
            /**
             * 设置专辑类型按钮点击事件
             */
            binding.btnAlbumType.setOnClickListener {
                callbackFunction.albumListClicked()
            }
            /**
             * 设置歌单类型按钮点击事件
             */
            binding.btnPlaylistSheetType.setOnClickListener {
                callbackFunction.playlistSheetClicked()
            }
            /**
             * 设置歌手类型按钮点击事件
             */
            binding.btnArtistType.setOnClickListener {
                callbackFunction.artistListClicked()
            }
        }
    }

    /**
     * 首页横向滑动父项视图容器
     */
    inner class OnlineMusicHomeSmallViewHolder(
        binding: OnlineMusicHomeOtherSmallItemBinding
    ): ViewBindViewHolder<OnlineMusicHomeOtherSmallItemBinding>(binding){

        init {
            // 创建横向嵌套RV时设置布局和缓存池
            (binding.rvSmallItem.layoutManager as? LinearLayoutManager)?.apply {
                recycleChildrenOnDetach = true
                initialPrefetchItemCount = 3
                binding.rvSmallItem.layoutManager = this
            }

        }

        /**
         * 设置横向嵌套RV的内容
         */
        fun bind(item: OnlineMusicHomeSmallItem){
            val adapter = binding.rvSmallItem.adapter?.let {
                it as InnerSmallItemRVAdapter
            } ?: run {
                val adapter = InnerSmallItemRVAdapter(callback,item.type)
                binding.rvSmallItem.adapter = adapter
                adapter
            }
            adapter.submitList(item.innerSmallItems)
            // 设置查看更多点击事件（防止多次设置进行了一次）
            if(!binding.lookupMore.hasOnClickListeners() && item.showMore){
                binding.lookupMore.setOnClickListener {
                    callback.smallMoreClicked(item.type)
                }
            }
        }
    }

    override fun createMultiViewBinding(
        parent: ViewGroup,
        viewType: Int
    ): RecyclerView.ViewHolder? {
        return when(viewType){
            BaseItemData.LAYOUT_ONLINE_MUSIC_HOME_TYPE_BROWSE ->{
                TypeBrowseViewHolder(
                    OnlineMusicHomeTypeBrowseItemBinding.inflate(
                    LayoutInflater.from(parent.context),parent,false),homeItemFunctionCallback)
            }
            BaseItemData.LAYOUT_ONLINE_MUSIC_HOME_SMALL_ITEM ->{
                OnlineMusicHomeSmallViewHolder(
                    OnlineMusicHomeOtherSmallItemBinding.inflate(
                    LayoutInflater.from(parent.context),parent,false
                ))
            }
            else ->
                null
        }
    }

    override fun bindMultiItem(
        holder: RecyclerView.ViewHolder,
        position: Int,
        item: BaseItemData,
        payloads: MutableList<Any>,
        viewType: Int
    ) {
        when(viewType){
            BaseItemData.LAYOUT_ONLINE_MUSIC_HOME_TYPE_BROWSE ->{
                handleTypeBrowseItem(holder as TypeBrowseViewHolder,item as OnlineMusicHomeTypeBrowseItem)
            }
            BaseItemData.LAYOUT_ONLINE_MUSIC_HOME_SMALL_ITEM ->{
                handleHomeOtherSmallItem(holder as OnlineMusicHomeSmallViewHolder,item as OnlineMusicHomeSmallItem)
            }
        }
    }

    /**
     * 处理首页类型处理的内容
     */
    private fun handleTypeBrowseItem(holder: TypeBrowseViewHolder, itemOnlineMusicHome: OnlineMusicHomeTypeBrowseItem) {
        if(holder.binding.bannerOnlineMusicHome.adapter == null){
            holder.binding.bannerOnlineMusicHome.adapter = BannerShapeImageAdapter(
                bannerCallback,itemOnlineMusicHome.banners)
            holder.binding.bannerOnlineMusicHome.indicator = CircleIndicator(holder.binding.bannerOnlineMusicHome.context)
        }
    }

    /**
     * 处理首页其他小项（该小项有内嵌横滑的RecyclerView）
     */
    private fun handleHomeOtherSmallItem(holder: OnlineMusicHomeSmallViewHolder, item: OnlineMusicHomeSmallItem) {
        holder.binding.tvSmallItemTitle.text = item.title
        holder.binding.lookupMore.isVisible = item.showMore
        holder.bind(item)
    }

}

/**
 * 横向滑动子项的RecyclerView适配器
 *
 * @param type 当前横向滑动子项的类型
 */
class InnerSmallItemRVAdapter(
    private val smallItemClick: OnlineMusicHomeSmallItemCallback,
    private val type: Int
): ViewBindingAdapter<OnlineMusicHomeInnerSmallItemBinding,
        InnerSmallItemRVAdapter.InnerSmallItemViewHolder, OnlineMusicHomeInnerSmallItem>(
    OnlineMusicHomeInnerSmallItem.differCallback){

    /**
     * 横向滑动子项每一项的视图容器
     */
    inner class InnerSmallItemViewHolder(
        binding: OnlineMusicHomeInnerSmallItemBinding
    ): ViewBindViewHolder<OnlineMusicHomeInnerSmallItemBinding>(binding){

        var item: OnlineMusicHomeInnerSmallItem? = null
        init {
            binding.root.setOnClickListener {
                item?.let {
                    smallItemClick.smallItemClicked(type,it)
                }
            }
            binding.btnPlay.setOnClickListener {
                item?.let {
                    smallItemClick.smallItemClicked(type,it)
                }
            }
        }
    }

    override fun createViewBinding(
        parent: ViewGroup,
        viewType: Int
    ): InnerSmallItemViewHolder {
        return InnerSmallItemViewHolder(
            OnlineMusicHomeInnerSmallItemBinding.inflate(LayoutInflater.from(parent.context),
                parent,false))
    }

    override fun bindItem(
        holder: InnerSmallItemViewHolder,
        position: Int,
        item: OnlineMusicHomeInnerSmallItem,
        payloads: MutableList<Any>
    ) {
        holder.item = item
        holder.binding.tvInnerSmallItemTitle.text = item.title
        holder.binding.tvInnerSmallItemSubtitle.text = item.subtitle
        Glide.with(holder.binding.ivInnerSmallItem)
            .load(item.imageUrl)
            .placeholder(R.drawable.img_default_album_browse)
            .into(holder.binding.ivInnerSmallItem)

        // 播放按钮需要该音源可播放时开启
        holder.binding.btnPlay.isEnabled = item.playable
        // 整个View可点击是保证音源可播放或不是音源类型，而是其他类型
        holder.binding.root.isEnabled = item.playable || type != OnlineMusicHomeSmallItem.SMALL_ITEM_MUSIC
        holder.binding.btnPlay.isVisible = item.playable
    }
}


interface OnlineMusicHomeFunctionCallback{
    /**
     * 点击歌手列表按钮回调
     */
    fun artistListClicked()

    /**
     * 点击歌单列表按钮回调
     */
    fun playlistSheetClicked()

    /**
     * 点击专辑列表按钮回调
     */
    fun albumListClicked()
}

interface OnlineMusicHomeSmallItemCallback{
    /**
     * 子项内容点击回调
     */
    fun smallItemClicked(type:Int,item: OnlineMusicHomeInnerSmallItem)

    /**
     * 子项内容查看更多点击回调
     */
    fun smallMoreClicked(type:Int)
}